package DAO

import (
	"CSMS/database"
	"database/sql"
	"fmt"
	"github.com/gin-gonic/gin"
)

type Good struct {
	GoodNo    int            `db:"GoodNo"`
	GoodName  sql.NullString `db:"GoodName"`
	GoodPrice int            `db:"GoodPrice"`
}

//SelectGoodList 生成商品ginJson
func SelectGoodList() []gin.H {
	//变量
	var GoodListJson []gin.H
	var good Good

	//从数据库获取数据
	rows, err := database.DB.Query("SELECT * FROM good")
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	if err != nil {
		fmt.Printf("Query failed,err:%v", err)
		return GoodListJson
	}
	for rows.Next() {
		err = rows.Scan(&good.GoodNo, &good.GoodName, &good.GoodPrice)
		if err != nil {
			fmt.Printf("Scan failed,err:%v", err)
			return GoodListJson
		}
		GoodListJson = append(GoodListJson, gin.H{
			"GoodNo":    good.GoodNo,
			"GoodName":  good.GoodName,
			"GoodPrice": good.GoodPrice,
		})
	}
	//返回json
	return GoodListJson
}

//SelectALL 通过商品号数组生成商品对象数组
func SelectALLByNo(goodNo []int) []Good {
	var good Good
	var goods []Good
	for i := 0; i < len(goodNo); i++ {
		row := database.DB.QueryRow("SELECT * FROM good WHERE GoodNo=?", goodNo[i])
		err := row.Scan(&good.GoodNo, &good.GoodName, &good.GoodPrice)
		if err != nil {
			fmt.Println(err, "User.go")
			return nil
		}
		goods = append(goods, good)
	}
	return goods
}
